package annotationDemo.项目实战2_Hibernate;

import java.lang.reflect.Field;

/**
 * @author Ajie
 * @date 2023/8/3
 * @function
 *
 * 输出结果:select * from db_user where user_name = 'chy'
 */
public class Main {
    public static void main(String[] args) throws Exception{
        System.out.println("Main:main:"+FindUserByUserName("chy"));
    }
    //根据userName在数据库中进行查询
    public static String FindUserByUserName(String userName) throws Exception{
        StringBuilder sb = new StringBuilder();
        //1.获取class
        Class clazz = User.class;
        //2.获取table的名字
        boolean exists = clazz.isAnnotationPresent(Table.class);
        if(!exists)return null;
        Table t = (Table)clazz.getAnnotation(Table.class);
        String tableName = t.value();
        sb.append("select * from ").append(tableName).append("where 1=1");

        //3.获取userName字段
        Field field = clazz.getDeclaredField("userName");
        //4.处理每个字段对应的sql
        //4.1 拿到数据库字段名
        boolean fExists = field.isAnnotationPresent(Column.class);
        Column column = field.getAnnotation(Column.class);
        String columnName = column.value();
        //4.2 拿到字段的值
        String fieldValue = userName;
        //4.3 拼装sql
        sb.append(" and "+columnName+" = '"+fieldValue + "'");

        return sb.toString();
    }


}
